﻿using Comm.PublicClass;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using WsProtocol.IEC62056;
using WsProtocol.IEC62056MDL;

namespace Wasion.HHU.Common
{
    public class TestMeter : PtlBaseMeter
    {
        private static List<TestMeter> AllMeterLst = null;
        private const string tablename = "T_Meter62056"; //保存表数据的表名
        private static EasyDb nowdb = null;

        public TMeter62056 Meter62056; //62056协议中间层需要的表信息
        public List<ProObAttr> ObAttrLst { get; set; }  //62056协议属性类列表
        
        

        public TestMeter()
        {
            Meter62056 = new TMeter62056();
            ObAttrLst = new List<ProObAttr>();            
        }

        public void Dispose()
        {
            AllMeterLst.Remove(this);

            GC.SuppressFinalize(this);
        }

        //设表号虚方法
        protected override void SetMeterNO()
        {
            base.SetMeterSNO();
            Meter62056.MeterNO = this.MeterNO;
        }

        //设地址虚方法
        protected override void SetMeterCommAddr()
        {
            try
            {
                Meter62056.MeterCommAddr = Int16.Parse(this.MeterCommAddr);  //地址
            }
            catch
            { }
        }

        //设密码虚方法
        protected override void SetPassWord()
        {
            Meter62056.PassWord = this.PassWord;
        }

        //复制自身
        public TestMeter Copy()
        {
            //新建一个
            TestMeter newmeter = new TestMeter();

            //复制属性
            PropertyInfo[] fromFields = typeof(TestMeter).GetProperties();
            PubFunction.SetProperties(fromFields, this, newmeter);

            newmeter.Meter62056 = Meter62056.Copy();

            return newmeter;
        }

        public void Reset()
        {
            Meter62056.Reset();
            ObAttrLst.Clear();
            Status = string.Empty;
        }

        #region methods
        public static List<TestMeter> TableToList(DataTable dt)
        {
            List<TestMeter> list = new List<TestMeter>();
            foreach (DataRow dr in dt.Rows)
            {
                TestMeter m = GetModelByDataRow(dr);

                list.Add(m);
            }
            return list;
        }

        public static TestMeter GetModelByDataRow(DataRow dr)
        {
            TestMeter m = new TestMeter();
            try
            {
                m.SNO = Int16.Parse(dr["SNO"].ToString());  //表位
            }
            catch
            { }
            m.MeterID = dr["MeterID"].ToString();  //表ID
            m.MeterNO = dr["MeterNO"].ToString();  //表号        
            m.MeterName = dr["MeterName"].ToString();  //表名
            m.MeterCommAddr = dr["MeterCommAddr"].ToString();  //地址                
            try
            {
                m.Meter62056.AddrLen = Int16.Parse(dr["AddrLen"].ToString());  //地址长度
            }
            catch
            { }
            m.InstAddr = dr["InstAddr"].ToString();
            m.ProjectCode = dr["ProjectCode"].ToString();  //所属项目编号

            m.OrderNo = dr["OrderNo"].ToString();

            m.MeterAssetNO = dr["MeterAssetNO"].ToString();  //资产编号

            m.MeterDesc = dr["MeterDesc"].ToString();
            m.MClass = dr["MClass"].ToString();  //精度等级
            m.Voltage = dr["Voltage"].ToString();  //电压规格
            m.FCurrent = dr["FCurrent"].ToString();  //电流规格
            m.PConstant = dr["PConstant"].ToString();  //有功脉冲常数
            m.QConstant = dr["QConstant"].ToString();  //无功脉冲常数
            m.FPrecision = dr["FPrecision"].ToString();  //有功精度等级
            m.QPrecision = dr["QPrecision"].ToString();  //无功精度等级
            m.PassWord = dr["PassWord"].ToString();  //密码
            m.ConnectMode = dr["ConnectMode"].ToString();  //接线方式
            m.IPAndPort = dr["IPAndPort"].ToString();  //ip和端口
            m.Meter62056.AppProVersion = dr["AppProVersion"].ToString(); //应用层协议版本号
            m.Meter62056.ProConform = dr["ProConform"].ToString(); //协议一致性块
                                                                   //m.Meter62056.FuncConform = dr["FuncConform"].ToString(); //功能一致性块
            m.Meter62056.SendMaxSize = dr["SendMaxSize"].ToString();  //发送最大信息域长度
            m.Meter62056.RecMaxSize = dr["RecMaxSize"].ToString();  //接收最大信息域长度 
            m.Meter62056.SendMaxWindow = dr["SendMaxWindow"].ToString();  //发送窗口大小
            m.Meter62056.RecMaxWindow = dr["RecMaxWindow"].ToString(); //接收窗口大小
            m.Meter62056.APDUSize = dr["APDUSize"].ToString(); //最大可处理APDU尺寸
            try
            {
                m.Meter62056.ContextName = (RequirContext)int.Parse(dr["ContextName"].ToString());
            }
            catch { }
            try
            {
                m.Meter62056.SecurityModeExpand = (AuthenticationExpand)Int16.Parse(dr["SecurityMode"].ToString()); //安全验证等级
            }
            catch
            { }
            return m;
        }

        public static List<TestMeter> GetAllMeters()
        {
            AllMeterLst = new List<TestMeter>();
            return AllMeterLst;
        }

        /// <summary>
        /// 根据ID获取表对象
        /// </summary>
        /// <param name="aMeterID"></param>
        /// <returns></returns>
        public static TestMeter GetTestMeterByID(string aMeterID)
        {
            TestMeter ameter = null;
            if (AllMeterLst == null)
                GetAllMeters();
            for (int i = 0; i < AllMeterLst.Count; i++)
            {
                if (AllMeterLst[i].MeterID == aMeterID)
                {
                    ameter = AllMeterLst[i];
                    break;
                }
            }
            return ameter;
        }

        /// <summary>
        /// 根据表号获取表对象
        /// </summary>
        /// <param name="aMeterNO"></param>
        /// <returns></returns>
        public static TestMeter GetTestMetersByNO(string aMeterNO)
        {
            TestMeter ameter = null;
            if (AllMeterLst == null)
                GetAllMeters();
            for (int i = 0; i < AllMeterLst.Count; i++)
            {
                if (AllMeterLst[i].MeterNO == aMeterNO)
                {
                    ameter = AllMeterLst[i];
                    break;
                }
            }
            return ameter;
        }

        /// <summary>
        /// 根据项目编号获取表对象列表
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        public static List<TestMeter> GetMeterByProCode(string ProjectId,bool ReLoad)
        {
            if (AllMeterLst == null || ReLoad)
                GetAllMeters();
            if (string.IsNullOrEmpty(ProjectId))
                return AllMeterLst;
            List<TestMeter> meterlst = new List<TestMeter>();
            
            for (int i = 0; i < AllMeterLst.Count; i++)
            {
                if (AllMeterLst[i].ProjectCode == ProjectId)
                    meterlst.Add(AllMeterLst[i]);
            }
            return meterlst;
        }


        public int UpdateMeter(ref string errinfo)
        {
            int rs = 0;
            bool bExist = false;

            if (string.IsNullOrEmpty(MeterID))
            {
                MeterID = PtlBaseUIProPubFunc.GetNewId(tablename, "MeterID");
            }
            else
            {
                nowdb.Clear();
                nowdb.TableName = tablename;
                nowdb.SetWhereParameter(true, "MeterID", "=", MeterID, EasyDataType.Number);
                DataTable dt = nowdb.Select();
                if (dt != null && dt.Rows.Count > 0)
                    bExist = true;
            }
            nowdb.Clear();
            nowdb.TableName = tablename;

            nowdb.SetFieldValue("SNO", SNO.ToString(), EasyDataType.Number);  //表位
            //nowdb.SetFieldValue("ProMeter_ID", ProMeter_ID, EasyDataType.String); 

            nowdb.SetFieldValue("MeterNO", MeterNO, EasyDataType.String);  //表号        
            nowdb.SetFieldValue("MeterName", MeterName, EasyDataType.String);  //表名
            nowdb.SetFieldValue("MeterCommAddr", MeterCommAddr.ToString(), EasyDataType.String);  //地址
            nowdb.SetFieldValue("AddrLen", Meter62056.AddrLen.ToString(), EasyDataType.Number);  //地址长度
            nowdb.SetFieldValue("ProjectCode", ProjectCode, EasyDataType.String);  //所属项目编号
            nowdb.SetFieldValue("OrderNo", OrderNo, EasyDataType.String);  //内部订单号
            nowdb.SetFieldValue("MeterAssetNO", MeterAssetNO, EasyDataType.String); //资产编号
            nowdb.SetFieldValue("InstAddr", InstAddr, EasyDataType.String);
            nowdb.SetFieldValue("MeterDesc", MeterDesc, EasyDataType.String);
            nowdb.SetFieldValue("MClass", MClass, EasyDataType.String);//精度等级

            nowdb.SetFieldValue("Voltage", Voltage, EasyDataType.String); //电压规格
            nowdb.SetFieldValue("FCurrent", FCurrent, EasyDataType.String);  //电流规格
            nowdb.SetFieldValue("PConstant", PConstant, EasyDataType.String);  //有功脉冲常数
            nowdb.SetFieldValue("QConstant", QConstant, EasyDataType.String);  //无功脉冲常数
            nowdb.SetFieldValue("FPrecision", FPrecision, EasyDataType.String); //有功精度等级
            nowdb.SetFieldValue("QPrecision", QPrecision, EasyDataType.String); //无功精度等级
            nowdb.SetFieldValue("PassWord", PassWord, EasyDataType.String);  //密码
            nowdb.SetFieldValue("ConnectMode", ConnectMode, EasyDataType.String);  //接线方式
            nowdb.SetFieldValue("IPAndPort", IPAndPort, EasyDataType.String);
            nowdb.SetFieldValue("AppProVersion", string.IsNullOrEmpty(Meter62056.AppProVersion) ? "06" : Meter62056.AppProVersion, EasyDataType.Number); //应用层协议版本号
            nowdb.SetFieldValue("ProConform", string.IsNullOrEmpty(Meter62056.ProConform) ? "007E1F" : Meter62056.ProConform, EasyDataType.String);  //协议一致性块
            //nowdb.SetFieldValue("FuncConform", string.IsNullOrEmpty(Meter62056.FuncConform) ? "0" : Meter62056.FuncConform, EasyDataType.String);  //功能一致性块
            nowdb.SetFieldValue("SendMaxSize", string.IsNullOrEmpty(Meter62056.SendMaxSize) ? "1024" : Meter62056.SendMaxSize, EasyDataType.Number);  //发送帧最大尺寸
            nowdb.SetFieldValue("RecMaxSize", string.IsNullOrEmpty(Meter62056.RecMaxSize) ? "1024" : Meter62056.RecMaxSize, EasyDataType.Number);  //接收帧最大尺寸
            nowdb.SetFieldValue("SendMaxWindow", string.IsNullOrEmpty(Meter62056.SendMaxWindow) ? "1" : Meter62056.SendMaxWindow, EasyDataType.Number);  //发送帧最大窗口尺寸
            nowdb.SetFieldValue("RecMaxWindow", string.IsNullOrEmpty(Meter62056.RecMaxWindow) ? "1" : Meter62056.RecMaxWindow, EasyDataType.Number);  //接收帧最大窗口尺寸
            nowdb.SetFieldValue("APDUSize", string.IsNullOrEmpty(Meter62056.APDUSize) ? "1024" : Meter62056.APDUSize, EasyDataType.Number);  //最大可处理APDU尺寸
            //nowdb.SetFieldValue("OutTime", string.IsNullOrEmpty(OutTime) ? "1800" : OutTime, EasyDataType.Number);  //应用连接超时时间
            //nowdb.SetFieldValue("SoftEditionDate", SoftEditionDate, EasyDataType.String);
            //nowdb.SetFieldValue("HardEdionDate", HardEdionDate, EasyDataType.String);
            //nowdb.SetFieldValue("FactoryExpand", FactoryExpand, EasyDataType.String);
            nowdb.SetFieldValue("SecurityMode", Meter62056.securitymodeexpand.ToString(), EasyDataType.String);
            nowdb.SetFieldValue("AddrLen", Meter62056.AddrLen.ToString(), EasyDataType.String);
            nowdb.SetFieldValue("ContextName", ((int)Meter62056.ContextName).ToString(), EasyDataType.String);
            

            if (bExist)
            {
                nowdb.SetWhereParameter(true, "MeterID", "=", MeterID, EasyDataType.Number);
                rs = nowdb.Update(ref errinfo);
            }
            else
            {
                nowdb.SetFieldValue("MeterID", MeterID, EasyDataType.Number);
                rs = nowdb.Insert(ref errinfo);
                if (rs > 0)
                    AllMeterLst.Add(this);
            }
            return rs;
        }

        /// <summary>
        /// 删除表
        /// </summary>
        /// <param name="errinfo"></param>
        /// <returns></returns>
        public int DeleteMeter(ref string errinfo)
        {
            nowdb.Clear();
            nowdb.TableName = tablename;
            nowdb.SetWhereParameter(true, "MeterID", "=", MeterID, EasyDataType.String);
            int rs = nowdb.Delete(ref errinfo);
            if (rs > 0)
                this.Dispose();
            return rs;
        }

        /// <summary>
        /// 清空某项目下包含的表
        /// </summary>
        /// <param name="ProjectCode"></param>
        /// <returns></returns>
        public static int DeleteMeterByProCode(string ProjectCode, ref string errinfo)
        {
            int rs = 0;
            for (int i = 0; i < AllMeterLst.Count; i++)
            {
                if (AllMeterLst[i].ProjectCode == ProjectCode)
                {
                    rs = AllMeterLst[i].DeleteMeter(ref errinfo);
                    if (rs < 0)
                        return rs;
                }
            }
            return rs;
        }

        #endregion


        /// <summary>
        /// 加载表名
        /// </summary>
        public static List<string> LoadMeterName()
        {
            if (AllMeterLst == null)
                GetAllMeters();
            List<string> tmplst = new List<string>();

            for (int i = 0; i < AllMeterLst.Count; i++)
                if (!string.IsNullOrEmpty(AllMeterLst[i].MeterName) && tmplst.IndexOf(AllMeterLst[i].MeterName) < 0)
                    tmplst.Add(AllMeterLst[i].MeterName);

            return tmplst;
        }

        /// <summary>
        /// 加载电流规格  
        /// </summary>
        public static List<string> LoadCurrent()
        {
            if (AllMeterLst == null)
                GetAllMeters();
            List<string> tmplst = new List<string>();
            for (int i = 0; i < AllMeterLst.Count; i++)
                if (!string.IsNullOrEmpty(AllMeterLst[i].FCurrent) && tmplst.IndexOf(AllMeterLst[i].FCurrent) < 0)
                    tmplst.Add(AllMeterLst[i].FCurrent);

            return tmplst;
        }
    }

    
}
